package collection.set;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

/**
 * HashSet也是线程不安全的
 */
public class SetNotSafeTest {

	/**
	 * CopyOnWriteArraySet的底层其实是使用了CopyOnWriteArrayList
	 *
	 * @throws InterruptedException
	 */
	@Test
	public void test() throws InterruptedException {

		//Set<String> set = new HashSet<>();
		//Set<String> set = Collections.synchronizedSet(new HashSet<>());
		Set<String> set = new CopyOnWriteArraySet<String>();

		for (int i = 0; i < 30; i++) {
			new Thread(() -> {
				set.add(UUID.randomUUID().toString().substring(0, 8));
				System.out.println(set);
			}, String.valueOf(i)).start();
		}
		TimeUnit.SECONDS.sleep(5);
	}
}
